package com.dinglexiao.service.impl;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dinglexiao.common.lang.Result;
import com.dinglexiao.dto.AccountDTO;
import com.dinglexiao.entity.User;
import com.dinglexiao.mapper.UserMapper;
import com.dinglexiao.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dinglexiao.utils.JwtUtils;
import com.dinglexiao.utils.SaltecreatUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dlx
 * @since 2020-09-16
 */

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserMapper userMapper;

    /***
    * @description:登录验证
    * @param accountDTO
	 * @param response
    * @return com.dinglexiao.common.lang.Result
    * @author dlx
    * @date 2020/9/18-10:50
    */
    @Override
    public Result validateLogin(AccountDTO accountDTO, HttpServletResponse response){
        //1.后端验证,根据姓名查找用户信息
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", accountDTO.getUsername()));
        Assert.notNull(user,"用户不存在！");
        //2.验证密码,通过MD5校验
        if(!user.getPassword().equals(getMD5Password(accountDTO.getPassword(),user.getSalt()))){
            return Result.fail("用户名或密码不正确!");
        }
        //3.验证通过，返回给用户一个token
        String token = jwtUtils.getToken(user.getId());
        //4.将token值存储在头信息中
        response.setHeader("token",token);
        response.setHeader("Access-Control-Expose-Headers","token");//设置跨域

        //更新用户最后的登录时间
        user.setLastLogin(LocalDateTime.now());
        userMapper.updateById(user);

        //5.返回用户信息
        return Result.success(MapUtil.builder()
                .put("id",user.getId())
                .put("username",user.getUsername())
                .put("avator",user.getAvatar())
                .put("email",user.getEmail())
                .map());
    }

    /***
    * @description:用户信息注册
    * @param user
    * @return com.dinglexiao.common.lang.Result
    * @author dlx
    * @date 2020/9/18-10:53
    */
    @Transactional
    @Override
    public Result registerAccount(User user) {
        //1.判断用户是否已经存在
        User user_search = userMapper.selectOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        if(user_search != null){
            return Result.fail("用户名已存在!");
        }
        //2.执行密码加密
        String salt = SaltecreatUtils.getSalt(4);
        user.setSalt(salt);
        user.setStatus(1);
        user.setCreated(LocalDateTime.now());
        user.setPassword(getMD5Password(user.getPassword(),salt));
        //3.保存到数据库并返回信息
        try {
            userMapper.insert(user);
            return Result.success(MapUtil.builder()
                    .put("id",user.getId())
                    .put("username",user.getUsername())
                    .put("avator",user.getAvatar())
                    .put("email",user.getEmail())
                    .map());
        }catch (Exception e){
            return Result.fail("注册失败！");
        }
    }

    //获取MD5加密+salt+hash散列的密码
    private String getMD5Password(String password,String salt){
        Md5Hash md5Hash = new Md5Hash(password,salt,1024);
        return md5Hash.toHex();
    }
}
